﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace MethodBox.WebServices
{
    class CommonAPI
    {
        /// <summary>
        /// 向MethodBox提交数据请求
        /// </summary>
        /// <param name="account">用户名</param>
        /// <param name="POSTURL">请求提交的地址</param>
        /// <param name="PostData">提交的数据(字符串)</param>
        /// <param name="NeedType">需要的许可证类型</param>
        /// <returns></returns>
        public static string RequestData(string POSTURL, string PostData, List<string> NeedType, bool apt_api = false, string account = "")
        {
            //发送请求的数据
            WebRequest myHttpWebRequest = WebRequest.Create(POSTURL);
            myHttpWebRequest.Method = "POST";
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byte1 = encoding.GetBytes(PostData);
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            myHttpWebRequest.ContentLength = byte1.Length;
            Stream newStream = myHttpWebRequest.GetRequestStream();
            newStream.Write(byte1, 0, byte1.Length);
            newStream.Close();
            //发送成功后接收返回的XML信息
            HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse(); string lcHtml = string.Empty;
            Encoding enc = Encoding.GetEncoding("UTF-8");
            Stream stream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(stream, enc);
            lcHtml = streamReader.ReadToEnd();
            if (apt_api)
            {
                if (lcHtml.StartsWith("您")) { return lcHtml; }
                if (NeedType.Contains(lcHtml)) { return $"您好，{account}。"; }
                else { return $"您的许可证类型为{lcHtml}。\n使用此应用需要的许可证类型与您的许可证不符，请前往获取能够使用的许可证。"; }
            }
            else
            {
                return lcHtml;
            }
        }
    }
}
